<script setup>
import { ref, onMounted, watch, computed, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElSelect, ElOption } from 'element-plus'
import 'element-plus/dist/index.css'
import SchoolInfo from './SchoolInfo.vue'
import SelectGroup from './SelectGroup.vue'
import RoundsInfo from './RoundsInfo.vue'
import MatchCard from './MatchCard.vue'
import axios from 'axios'

const route = useRoute()
const matchId = route.params.id
console.log('路由参数:', route.params)
console.log('比赛ID:', matchId)

// 添加定时器引用和刷新状态
const dataRefreshTimer = ref(null)
const isRefreshing = ref(false)
const lastUpdateTime = ref(null)

// 添加baseURL配置
const baseURL = 'http://localhost:3000'
axios.defaults.baseURL = baseURL

const matchData = ref(null)
const selectedCubeType = ref('')
const selectedRound = ref('第一轮')

// 获取比赛详情
const fetchMatchDetails = async () => {
  // 如果正在刷新，则不执行
  if (isRefreshing.value) {
    console.log('正在刷新数据，跳过本次刷新')
    return
  }
  
  try {
    isRefreshing.value = true
    console.log('开始获取比赛详情，比赛ID:', matchId)
    
    // 保存当前选中的魔方类型和轮次
    const currentCubeType = selectedCubeType.value
    const currentRound = selectedRound.value
    
    // 获取魔方类型
    let cubeTypesData = []
    try {
      const typesResponse = await axios.get('/api/cube-types')
      cubeTypesData = typesResponse.data
      console.log('魔方类型数据:', cubeTypesData)
    } catch (error) {
      console.error('获取魔方类型失败:', error)
      // 使用默认魔方类型
      cubeTypesData = [
        { id: 1, name: '二阶魔方' },
        { id: 2, name: '三阶魔方' },
        { id: 3, name: '金字塔魔方' },
        { id: 4, name: '斜转魔方' }
      ]
    }
    
    // 获取比赛详细信息
    const response = await axios.get(`/api/matches/${matchId}`)
    console.log('比赛详情响应:', response.data)
    
    // 处理返回的数据
    const data = response.data
    
    // 单独获取抽签结果
    try {
      const drawResultsResponse = await axios.get(`/api/matches/${matchId}/draw-results`)
      console.log('抽签结果响应:', drawResultsResponse.data)
      data.draw_results = drawResultsResponse.data
    } catch (error) {
      console.error('获取抽签结果失败:', error)
      data.draw_results = []
    }
    
    // 获取比赛成绩数据
    try {
      const scoresResponse = await axios.get(`/api/scores?match_id=${matchId}`)
      console.log('成绩数据响应:', scoresResponse.data)
      data.scores = scoresResponse.data
    } catch (error) {
      console.error('获取成绩失败:', error)
      data.scores = []
    }
    
    // 如果仍然没有抽签结果，使用测试数据
    if (!data.draw_results || !data.draw_results.length) {
      console.log('使用测试抽签数据')
      data.draw_results = [
        { 
          player_id: 1, player_name: '张三', school_id: data.home_school_id, 
          school_name: data.home_school_name, draw_number: 1, seat_number: 1 
        },
        { 
          player_id: 2, player_name: '李四', school_id: data.away_school_id, 
          school_name: data.away_school_name, draw_number: 2, seat_number: 1 
        },
        { 
          player_id: 3, player_name: '王五', school_id: data.home_school_id, 
          school_name: data.home_school_name, draw_number: 3, seat_number: 2 
        },
        { 
          player_id: 4, player_name: '赵六', school_id: data.away_school_id, 
          school_name: data.away_school_name, draw_number: 4, seat_number: 2 
        },
        { 
          player_id: 5, player_name: '孙七', school_id: data.home_school_id, 
          school_name: data.home_school_name, draw_number: 5, seat_number: 3 
        },
        { 
          player_id: 6, player_name: '周八', school_id: data.away_school_id, 
          school_name: data.away_school_name, draw_number: 6, seat_number: 3 
        },
        { 
          player_id: 7, player_name: '吴九', school_id: data.home_school_id, 
          school_name: data.home_school_name, draw_number: 7, seat_number: 4 
        },
        { 
          player_id: 8, player_name: '郑十', school_id: data.away_school_id, 
          school_name: data.away_school_name, draw_number: 8, seat_number: 4 
        },
        { 
          player_id: 9, player_name: '冯十一', school_id: data.home_school_id, 
          school_name: data.home_school_name, draw_number: 9, seat_number: 5 
        },
        { 
          player_id: 10, player_name: '陈十二', school_id: data.away_school_id, 
          school_name: data.away_school_name, draw_number: 10, seat_number: 5 
        }
      ]
    }
    
    // 处理抽签结果，创建轮次数据
    const rounds = {
      round1: {}, // 第一轮
      round2: {}, // 第二轮
      round3: {}  // 第三轮
    }
    
    if (data.draw_results && data.draw_results.length > 0) {
      // 按座位号分组
      const groupedBySeatNumber = {}
      data.draw_results.forEach(result => {
        if (!groupedBySeatNumber[result.seat_number]) {
          groupedBySeatNumber[result.seat_number] = []
        }
        groupedBySeatNumber[result.seat_number].push(result)
      })
      
      // 获取所有座位号（最多10张桌子）
      const seatNumbers = Object.keys(groupedBySeatNumber)
        .sort((a, b) => parseInt(a) - parseInt(b))
        .slice(0, 10)
      
      // 为每个座位号创建轮次数据（每个座位号都要参加三轮比赛）
      seatNumbers.forEach(seatNumber => {
        const players = groupedBySeatNumber[seatNumber]
        const tableId = `table${seatNumber}` // 桌子ID
        
        // 每个座位有2名选手，一名来自主场学校，一名来自客场学校
        const homePlayer = players.find(p => p.school_id === data.home_school_id)
        const awayPlayer = players.find(p => p.school_id === data.away_school_id)
        
        if (homePlayer && awayPlayer) {
          // 为该桌子创建三轮比赛数据
          for (let i = 1; i <= 3; i++) {
            const roundKey = `round${i}`
            
            // 根据 cube_type_id 和 round_number 获取该轮该座位相关的成绩数据
            const homePlayerScores = data.scores?.filter(score => 
              score.player_id === homePlayer.player_id && 
              score.round_number === i
            ) || []
            
            const awayPlayerScores = data.scores?.filter(score => 
              score.player_id === awayPlayer.player_id && 
              score.round_number === i
            ) || []
            
            // 为每种魔方类型创建数据结构
            cubeTypesData.forEach(cubeType => {
              if (!rounds[roundKey][tableId]) {
                rounds[roundKey][tableId] = {}
              }
              
              // 获取特定魔方类型的成绩
              const homePlayerScore = homePlayerScores.find(score => score.cube_type_id === cubeType.id)
              const awayPlayerScore = awayPlayerScores.find(score => score.cube_type_id === cubeType.id)
              
              rounds[roundKey][tableId][cubeType.id] = {
                home_player: {
                  id: homePlayer.player_id,
                  name: homePlayer.player_name,
                  school_id: homePlayer.school_id,
                  school_name: homePlayer.school_name,
                  score: homePlayerScore?.score || null,  // 添加成绩
                  unsolved: homePlayerScore?.is_completed === 0,  // 是否未解决
                  penalty: false,   // 是否有惩罚
                  draw_number: homePlayer.draw_number,  // 抽签号
                  seat_number: homePlayer.seat_number  // 座位号
                },
                away_player: {
                  id: awayPlayer.player_id,
                  name: awayPlayer.player_name,
                  school_id: awayPlayer.school_id,
                  school_name: awayPlayer.school_name,
                  score: awayPlayerScore?.score || null,  // 添加成绩
                  unsolved: awayPlayerScore?.is_completed === 0,  // 是否未解决
                  penalty: false,   // 是否有惩罚
                  draw_number: awayPlayer.draw_number,  // 抽签号
                  seat_number: awayPlayer.seat_number  // 座位号
                },
                winner_id: null, // 暂无获胜者
                status: 'pending', // 待比赛状态
                table_id: tableId, // 添加桌号标识
                table_number: parseInt(seatNumber),
                cube_type_id: cubeType.id, // 添加魔方类型ID
                cube_type_name: cubeType.name // 添加魔方类型名称
              }
              
              // 如果双方都有成绩，确定获胜者
              if (homePlayerScore?.score !== undefined && awayPlayerScore?.score !== undefined) {
                const homeScore = parseFloat(homePlayerScore.score)
                const awayScore = parseFloat(awayPlayerScore.score)
                
                if (!isNaN(homeScore) && !isNaN(awayScore)) {
                  if (homePlayerScore.is_completed && !awayPlayerScore.is_completed) {
                    rounds[roundKey][tableId][cubeType.id].winner_id = homePlayer.player_id
                    rounds[roundKey][tableId][cubeType.id].status = 'completed'
                  } else if (!homePlayerScore.is_completed && awayPlayerScore.is_completed) {
                    rounds[roundKey][tableId][cubeType.id].winner_id = awayPlayer.player_id
                    rounds[roundKey][tableId][cubeType.id].status = 'completed'
                  } else if (homePlayerScore.is_completed && awayPlayerScore.is_completed) {
                    if (homeScore < awayScore) {
                      rounds[roundKey][tableId][cubeType.id].winner_id = homePlayer.player_id
                    } else {
                      rounds[roundKey][tableId][cubeType.id].winner_id = awayPlayer.player_id
                    }
                    rounds[roundKey][tableId][cubeType.id].status = 'completed'
                  }
                }
              }
            })
          }
        }
      })
    }
    
    // 创建所有魔方类型的数据结构
    const cubeTypes = {}
    
    // 将API返回的魔方类型转换为组件需要的格式
    const availableCubeTypes = cubeTypesData.map(type => {
      // 从完整名称中提取简称
      const shortName = type.name.replace(/魔方$/, '')
      return {
        id: type.id,
        name: shortName, // 简称，如"三阶"
        display_name: type.name // 完整名称，如"三阶魔方"
      }
    })
    
    // 为每种魔方类型创建对应的数据
    availableCubeTypes.forEach(type => {
      // 为每种魔方类型复制一份轮次数据
      cubeTypes[type.name] = {
        rounds: JSON.parse(JSON.stringify(rounds)) // 深拷贝轮次数据
      }
    })
    
    // 初始化数据结构
    const processedData = {
      ...data,
      home_school: data.home_school_name,
      away_school: data.away_school_name,
      // 优先使用数据库返回的short_name字段
      home_school_short_name: data.home_school_short_name || data.venue_name || data.home_school_name,
      away_school_short_name: data.away_school_short_name || data.away_school_name,
      home_group_code: data.home_group_code,
      away_group_code: data.away_group_code,
      total_rounds: 3, // 比赛总轮数固定为3轮
      current_status: {
        completed_rounds: calculateCompletedRounds(rounds)
      },
      // 使用创建的魔方类型数据结构
      cube_types: cubeTypes,
      // 可用的魔方类型
      available_cube_types: availableCubeTypes
    }
    
    // 设置选中的魔方类型，保持用户的选择，或者默认选第一个
    if (currentCubeType && availableCubeTypes.some(type => type.name === currentCubeType)) {
      selectedCubeType.value = currentCubeType
    } else if (availableCubeTypes.length > 0) {
      selectedCubeType.value = availableCubeTypes[0].name
    }
    
    // 保持用户选择的轮次
    selectedRound.value = currentRound || '第一轮'
    
    // 保存处理后的数据
    matchData.value = processedData
    
    console.log('处理后的比赛数据:', matchData.value)
    
    // 更新最后刷新时间
    lastUpdateTime.value = new Date()
  } catch (error) {
    console.error('获取比赛详情失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态码:', error.response.status)
    }
  } finally {
    isRefreshing.value = false
  }
}

// 添加监听器来观察数据变化
watch(selectedCubeType, (newValue) => {
  console.log('魔方类型变化:', newValue)
  console.log('对应的轮次数据:', matchData.value?.cube_types[newValue]?.rounds)
})

// 添加监听器来观察整个比赛数据的变化
watch(matchData, (newValue) => {
  console.log('比赛数据变化:', newValue)
}, { deep: true })

// 计算主场得分
const homeScore = computed(() => {
  if (!matchData.value || !matchData.value.cube_types) return 0
  let score = 0
  Object.values(matchData.value.cube_types).forEach(cubeType => {
    if (cubeType && cubeType.rounds) {
      Object.values(cubeType.rounds).forEach(round => {
        if (round?.winner_id === round?.home_player?.id) {
          score++
        }
      })
    }
  })
  return score
})

// 计算客场得分
const awayScore = computed(() => {
  if (!matchData.value || !matchData.value.cube_types) return 0
  let score = 0
  Object.values(matchData.value.cube_types).forEach(cubeType => {
    if (cubeType && cubeType.rounds) {
      Object.values(cubeType.rounds).forEach(round => {
        if (round?.winner_id === round?.away_player?.id) {
          score++
        }
      })
    }
  })
  return score
})

// 根据选中的轮次获取当前应该显示的桌子数据
const getCurrentRoundTables = computed(() => {
  if (!matchData.value || !matchData.value.cube_types || !selectedCubeType.value) {
    console.log('数据不完整，无法获取桌子数据');
    return {};
  }
  
  // 检查 cube_types 是否存在选中的类型
  if (!matchData.value.cube_types[selectedCubeType.value]) {
    console.log('未找到选中的魔方类型数据:', selectedCubeType.value);
    return {};
  }
  
  // 根据选中的轮次确定要显示哪一轮的数据
  let roundKey = 'round1';
  if (selectedRound.value === '第二轮') {
    roundKey = 'round2';
  } else if (selectedRound.value === '第三轮') {
    roundKey = 'round3';
  }
  
  // 检查是否存在该轮次数据
  const roundData = matchData.value.cube_types[selectedCubeType.value].rounds[roundKey];
  if (!roundData) {
    console.log('未找到该轮次数据:', roundKey);
    return {};
  }
  
  // 选中的魔方类型对应的ID
  const selectedCubeTypeObj = matchData.value.available_cube_types.find(
    type => type.name === selectedCubeType.value
  );
  
  if (!selectedCubeTypeObj) {
    console.log('未找到选中的魔方类型对象:', selectedCubeType.value);
    return {};
  }
  
  const selectedCubeTypeId = selectedCubeTypeObj.id;
  
  // 过滤出当前魔方类型的数据
  const filteredRoundData = {};
  
  // 遍历所有桌子
  Object.entries(roundData).forEach(([tableId, tableData]) => {
    // 获取当前魔方类型的数据
    const cubeTypeData = tableData[selectedCubeTypeId];
    if (cubeTypeData) {
      filteredRoundData[tableId] = cubeTypeData;
    }
  });
  
  return filteredRoundData;
});

// 计算完成的轮次数
const calculateCompletedRounds = (rounds) => {
  const completedRounds = [0, 0, 0];  // 记录每个轮次的完成状态
  
  // 检查每个轮次
  for (let i = 1; i <= 3; i++) {
    const roundKey = `round${i}`;
    const tables = Object.values(rounds[roundKey] || {});
    
    // 如果该轮次所有桌子都已完成，则标记该轮次为已完成
    if (tables.length > 0 && tables.every(table => table.status === 'completed')) {
      completedRounds[i-1] = 1;
    }
  }
  
  // 返回已完成的轮次数
  return completedRounds.reduce((sum, val) => sum + val, 0);
};

// 格式化最后更新时间
const formatUpdateTime = (time) => {
  if (!time) return '尚未刷新';
  
  const now = new Date();
  const diff = Math.floor((now - time) / 1000); // 秒数差
  
  if (diff < 60) {
    return `${diff}秒前`;
  } else if (diff < 3600) {
    return `${Math.floor(diff / 60)}分钟前`;
  } else {
    const hours = time.getHours().toString().padStart(2, '0');
    const minutes = time.getMinutes().toString().padStart(2, '0');
    const seconds = time.getSeconds().toString().padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
  }
};

onMounted(() => {
  fetchMatchDetails()
  
  // 设置定时器，每5秒刷新一次数据
  dataRefreshTimer.value = setInterval(() => {
    console.log('自动刷新数据...')
    fetchMatchDetails()
  }, 5000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (dataRefreshTimer.value) {
    clearInterval(dataRefreshTimer.value)
    dataRefreshTimer.value = null
    console.log('清除数据刷新定时器')
  }
})
</script>

<template>
  <div class="match-container" v-if="matchData">
    <div class="header">
      <SchoolInfo 
        :school-name="matchData.home_school" 
        :logo-src="'/img/school-logo-home.svg'" 
        :alt-text="'主队校徽'" 
        :score="homeScore"
        :group="matchData.home_group_code"
        class="home"
      />
      
      <SelectGroup 
        v-model:selected-cube-type="selectedCubeType" 
        :cube-types="matchData.available_cube_types" 
        v-model:selected-round="selectedRound" 
        :round-types="['第一轮', '第二轮', '第三轮']"
        class="select-group-wrapper"
      />
      
      <SchoolInfo 
        :school-name="matchData.away_school" 
        :logo-src="'/img/school-logo-away.svg'" 
        :alt-text="'客队校徽'" 
        :score="awayScore"
        :group="matchData.away_group_code"
        class="away"
      />
    </div>

    <div class="status-bar">
      <div class="refresh-status" v-if="isRefreshing">
        <span class="refresh-icon">⟳</span>
        数据刷新中...
      </div>
      <div class="refresh-status" v-else>
        <span class="auto-refresh-info">数据每5秒自动刷新</span>
        <span class="last-update">上次更新: {{ formatUpdateTime(lastUpdateTime) }}</span>
      </div>
    </div>

    <RoundsInfo 
      :totalRounds="matchData.total_rounds"
      :completedRounds="matchData.current_status?.completed_rounds"
    />

    <div class="match-grid">
      <MatchCard
        v-for="(tableData, tableKey) in getCurrentRoundTables"
        :key="tableKey"
        :match-data="matchData"
        :round-data="tableData"
        :selected-cube-type="selectedCubeType"
        :selected-round="selectedRound"
        :table-number="tableData.table_number"
      />
    </div>
  </div>
  <div v-else class="loading">
    加载中...
  </div>
</template>

<style scoped>
.match-container {
  max-width: 1500px;
  margin: 0 auto;
  padding: 15px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.match-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
  padding: 20px;
  max-width: 1500px;
  margin: 0 auto;
}

.loading {
  text-align: center;
  padding: 40px;
  font-size: 18px;
  color: #909399;
}

.home :deep(.score-badge) {
  background-color: #409EFF;
}

.away :deep(.score-badge) {
  background-color: #F56C6C;
}

.select-group-wrapper {
  min-width: 200px;
  flex: 0 0 auto;
}

.status-bar {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 8px 15px;
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.refresh-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.refresh-icon {
  display: inline-block;
  animation: spin 1s linear infinite;
  font-size: 16px;
}

.auto-refresh-info {
  color: #909399;
}

.last-update {
  color: #909399;
  font-size: 12px;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
